#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#define NUM 5
int ticket = 10;
pthread_mutex_t lock;//互斥量
void* routine(void* arg)
{
	while(1)
	{
		pthread_mutex_lock(&lock);
		//临界区
		if(ticket > 0)
		{
			sleep(1);
			printf("%x:get a ticket!--Ticket Num:%d\n",pthread_self(),ticket);
			ticket--;
			pthread_mutex_unlock(&lock);
			usleep(1000);
		}
		else
		{
			pthread_mutex_unlock(&lock);
			break;
		}
	}
	return NULL;
}
int main()
{
	pthread_mutex_init(&lock,NULL);
	pthread_t n[NUM];
	for(int i = 0;i < NUM; ++i)
	{
		pthread_create(n+i,NULL,routine,NULL);
	}
	for(int i = 0;i < NUM; ++i)
	{
		pthread_join(n[i],NULL);
	}
	pthread_mutex_destroy(&lock);
	printf("pthreads done...\n");
	return 0;
}
